<template>
  <el-scrollbar class="h-full">
    <el-card>
      <!-- 日程提醒设置 -->
      <SettingItem title="提醒" description="设置具体的提醒，系统将在指定时间提醒您">
        <el-button type="primary" :icon="Plus" @click="showAddTimeDialog"> 添加提醒 </el-button>
      </SettingItem>

      <!-- 提醒列表表格 -->
      <div class="mt-4">
        <el-table :data="reminderList" stripe style="width: 100%" v-loading="tableLoading">
          <el-table-column prop="title" label="提醒标题" width="150" />
          <el-table-column prop="type" label="提醒类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="description"
            label="提醒详情"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column prop="firstRemindTime" label="首次提醒时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.firstRemindTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="nextRemindTime" label="下次提醒时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.nextRemindTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ getStatusLabel(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空状态 -->
        <el-empty v-if="!tableLoading && reminderList.length === 0" description="暂无提醒数据" />
        <!-- 分页 -->
        <div class="flex justify-center mt-4">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑提醒对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增提醒' : '编辑提醒'"
      v-model="addTimeDialogVisible"
      width="600px"
      destroy-on-close
      :before-close="handleCloseAddTimeDialog"
    >
      <el-form ref="timeFormRef" :model="timeFormData" :rules="timeFormRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="提醒标题" prop="title">
              <el-input
                v-model="timeFormData.title"
                placeholder="请输入提醒标题，例如：上午用药提醒"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="14">
            <el-form-item label="提醒类型" prop="type">
              <el-select
                v-model="timeFormData.type"
                placeholder="请选择提醒类型"
                style="width: 100%"
              >
                <el-option label="用药提醒" value="MEDICATION" />
                <el-option label="康复提醒" value="REHAB" />
                <el-option label="复诊提醒" value="CONSULTATION" />
                <el-option label="自定义提醒" value="CUSTOM" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="提醒详情" prop="description">
          <el-input
            v-model="timeFormData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入提醒详情，例如：请服用降压药1粒，饭后服用"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="首次提醒时间" prop="firstRemindTime">
              <el-date-picker
                v-model="timeFormData.firstRemindTime"
                type="datetime"
                placeholder="选择首次提醒时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次提醒时间" prop="nextRemindTime">
              <el-date-picker
                v-model="timeFormData.nextRemindTime"
                type="datetime"
                placeholder="选择下次提醒时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="重复规则">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-select
                v-model="timeFormData.recurrenceRule.frequency"
                placeholder="选择重复频率"
                style="width: 100%"
              >
                <el-option label="不重复" value="NONE" />
                <el-option label="每天" value="DAILY" />
                <el-option label="每周" value="WEEKLY" />
                <el-option label="每月" value="MONTHLY" />
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-input-number
                v-model="timeFormData.recurrenceRule.interval"
                :min="1"
                :max="99"
                placeholder="间隔"
                :disabled="timeFormData.recurrenceRule.frequency === 'NONE'"
              />
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddTimeDialog">取消</el-button>
          <el-button type="primary" @click="handleAddTime" :loading="submitLoading">
            {{ dialogType === 'add' ? '添加' : '更新' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import type { MedicationSettings, Medication, MedicationTime } from '@/types/settings'
import SettingItem from '@/components/common/SettingItem.vue'
import { createReminder, fetchList, updateReminder, deleteReminder } from '@/api/reminder'
import { useUserStore } from '../../../store/user'

const userStore = useUserStore()

// 表格数据
const reminderList = ref([])
const tableLoading = ref(false)
const submitLoading = ref(false)

// 分页数据
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

// 对话框相关
const dialogType = ref<'add' | 'edit'>('add')
const addTimeDialogVisible = ref(false)
const timeFormRef = ref()

// 表单数据结构
const defaultForm = {
  id: null,
  userId: null,
  title: '',
  type: '',
  description: '',
  firstRemindTime: null,
  nextRemindTime: null,
  recurrenceRule: {
    frequency: 'DAILY',
    interval: 1
  },
  status: 'PENDING'
}
const timeFormData = ref({ ...defaultForm })

// 表单验证规则
const timeFormRules = {
  title: [{ required: true, message: '请输入提醒标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择提醒类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入提醒详情', trigger: 'blur' }],
  firstRemindTime: [{ required: true, message: '请选择首次提醒时间', trigger: 'change' }],
  nextRemindTime: [{ required: true, message: '请选择下次提醒时间', trigger: 'change' }],
  status: [{ required: true, message: '请选择提醒状态', trigger: 'change' }]
}

/**
 * 获取提醒列表
 */
const getReminderList = async () => {
  try {
    tableLoading.value = true
    const response = await fetchList({
      page: pagination.value.page,
      limit: pagination.value.limit,
      userId: userStore.userId
    })

    if (response.data?.list) {
      reminderList.value = response.data.list
      pagination.value.total = response.data.total || 0
    } else {
      reminderList.value = response.data || []
      pagination.value.total = reminderList.value.length
    }
  } catch (error) {
    console.error('获取提醒列表失败:', error)
    ElMessage.error('获取提醒列表失败')
  } finally {
    tableLoading.value = false
  }
}

/**
 * 显示新增提醒对话框
 */
const showAddTimeDialog = () => {
  timeFormData.value = { ...defaultForm }
  dialogType.value = 'add'
  addTimeDialogVisible.value = true
}

/**
 * 编辑提醒
 */
const handleEdit = (row: any) => {
  timeFormData.value = {
    ...row,
    recurrenceRule:
      typeof row.recurrenceRule === 'string'
        ? JSON.parse(row.recurrenceRule)
        : row.recurrenceRule || { frequency: 'DAILY', interval: 1 }
  }
  dialogType.value = 'edit'
  addTimeDialogVisible.value = true
}

/**
 * 删除提醒
 */
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要删除提醒"${row.title}"吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteReminder(row.id)
    ElMessage.success('删除成功')
    await getReminderList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

/**
 * 关闭提醒对话框
 */
const handleCloseAddTimeDialog = () => {
  timeFormData.value = { ...defaultForm }
  if (timeFormRef.value) {
    timeFormRef.value.resetFields()
  }
  addTimeDialogVisible.value = false
}

/**
 * 添加/更新提醒
 */
const handleAddTime = async () => {
  if (!timeFormRef.value) return

  await timeFormRef.value.validate(async (valid: any) => {
    if (!valid) return

    try {
      submitLoading.value = true
      timeFormData.value.userId = userStore.userId

      // 转换 recurrenceRule 为字符串格式
      const formData = {
        ...timeFormData.value,
        recurrenceRule: JSON.stringify(timeFormData.value.recurrenceRule)
      }

      if (dialogType.value === 'add') {
        await createReminder(formData)
        ElMessage.success('添加成功')
      } else {
        await updateReminder(formData)
        ElMessage.success('更新成功')
      }

      handleCloseAddTimeDialog()
      await getReminderList()
    } catch (error) {
      console.error('操作失败:', error)
      ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
    } finally {
      submitLoading.value = false
    }
  })
}

/**
 * 分页大小改变
 */
const handleSizeChange = (val: number) => {
  pagination.value.limit = val
  pagination.value.page = 1
  getReminderList()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (val: number) => {
  pagination.value.page = val
  getReminderList()
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

/**
 * 获取类型标签样式
 */
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    MEDICATION: 'success',
    REHAB: 'info',
    CONSULTATION: 'warning',
    CUSTOM: 'primary'
  }
  return typeMap[type] || 'info'
}

/**
 * 获取类型标签文本
 */
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    MEDICATION: '用药提醒',
    REHAB: '康复提醒',
    CONSULTATION: '复诊提醒',
    CUSTOM: '自定义提醒'
  }
  return typeMap[type] || type
}

/**
 * 获取状态标签样式
 */
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    PENDING: 'info',
    TRIGGERED: 'warning',
    COMPLETED: 'success',
    CANCELLED: 'info',
    PAUSED: 'warning',
    FAILED: 'danger'
  }
  return statusMap[status] || 'info'
}

/**
 * 获取状态标签文本
 */
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    PENDING: '待处理',
    TRIGGERED: '已触发',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
    PAUSED: '已暂停',
    FAILED: '失败'
  }
  return statusMap[status] || status
}

// 组件挂载时获取数据
onMounted(() => {
  getReminderList()
})
</script>

<style scoped lang="scss">
.dialog-footer {
  @apply flex justify-end gap-2;
}

.el-table {
  margin-top: 16px;
}

.el-tag {
  font-size: 12px;
}
</style>
